#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os
import json
import subprocess
from PyQt5.QtWidgets import (QApplication, QMainWindow, QListWidget, QPushButton, 
                            QVBoxLayout, QHBoxLayout, QWidget, QMessageBox, 
                            QDialog, QLineEdit, QFormLayout, QCheckBox, QFileDialog,
                            QLabel, QTextEdit, QStatusBar, QFrame, QProgressBar,
                            QTextBrowser, QTabWidget)
from PyQt5.QtCore import QTimer, Qt, QThread, pyqtSignal
from PyQt5.QtGui import QFont, QColor

class WiFiInfo:
    def __init__(self, ssid="", password="", use_static_ip=False, ip_address="", gateway="", remark=""):
        self.ssid = ssid
        self.password = password
        self.use_static_ip = use_static_ip
        self.ip_address = ip_address
        self.gateway = gateway
        self.remark = remark

class WiFiManager:
    def __init__(self):
        self.config_file = os.path.expanduser("~/.wifimanager_config.json")
        self.wifi_configs = {}
        self.version = "v1.1.3"  # 添加版本信息
        self.load_config()
    
    def load_config(self):
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    for ssid, config in data.items():
                        self.wifi_configs[ssid] = WiFiInfo(
                            ssid=config.get('ssid', ''),
                            password=config.get('password', ''),
                            use_static_ip=config.get('use_static_ip', False),
                            ip_address=config.get('ip_address', ''),
                            gateway=config.get('gateway', ''),
                            remark=config.get('remark', '')  # 添加备注信息加载
                        )
            except Exception as e:
                QMessageBox.warning(None, "警告", f"加载配置时出错: {e}")
    
    def save_config(self):
        try:
            data = {}
            for ssid, wifi_info in self.wifi_configs.items():
                data[ssid] = {
                    'ssid': wifi_info.ssid,
                    'password': wifi_info.password,
                    'use_static_ip': wifi_info.use_static_ip,
                    'ip_address': wifi_info.ip_address,
                    'gateway': wifi_info.gateway,
                    'remark': wifi_info.remark  # 保存备注信息
                }
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(data, f, indent=2, ensure_ascii=False)
        except Exception as e:
            QMessageBox.critical(None, "错误", f"保存配置时出错: {e}")
    
    def get_wifi_list(self):
        # 实现WiFi列表获取功能
        try:
            # 使用nmcli命令获取WiFi列表
            result = subprocess.run(['nmcli', '--terse', '--fields', 'SSID,SECURITY,SIGNAL', 'device', 'wifi', 'list'], 
                                   capture_output=True, text=True, timeout=10)
            if result.returncode == 0:
                wifi_list = []
                for line in result.stdout.strip().split('\n'):
                    if line:
                        parts = line.split(':')
                        if len(parts) >= 1 and parts[0]:  # 确保SSID不为空
                            wifi_list.append(parts[0])
                # 去重并返回
                return list(set(wifi_list))
            else:
                QMessageBox.warning(None, "警告", f"扫描WiFi错误: {result.stderr}")
                return []
        except subprocess.TimeoutExpired:
            QMessageBox.warning(None, "警告", "扫描WiFi超时")
            return []
        except FileNotFoundError:
            QMessageBox.critical(None, "错误", "找不到nmcli命令，请安装NetworkManager。")
            return []
        except Exception as e:
            QMessageBox.warning(None, "警告", f"扫描WiFi时出错: {e}")
            return []
    
    def add_wifi(self, ssid, password):
        self.wifi_configs[ssid] = WiFiInfo(ssid=ssid, password=password)
        self.save_config()
    
    def remove_wifi(self, ssid):
        if ssid in self.wifi_configs:
            del self.wifi_configs[ssid]
            self.save_config()
    
    def get_wifi_info(self, ssid):
        return self.wifi_configs.get(ssid, WiFiInfo())
    
    def set_static_ip_config(self, ssid, use_static_ip, ip_address, gateway):
        if ssid in self.wifi_configs:
            wifi_info = self.wifi_configs[ssid]
            wifi_info.use_static_ip = use_static_ip
            wifi_info.ip_address = ip_address
            wifi_info.gateway = gateway
            self.save_config()
    
    def connect_wifi(self, ssid):
        # 实现实际的WiFi连接逻辑
        try:
            # 检查是否已经连接到该WiFi
            current_wifi = self.get_current_connected_wifi()
            if current_wifi == ssid:
                QMessageBox.information(None, "信息", f"已经连接到 {ssid}")
                return True
                
            wifi_info = self.wifi_configs.get(ssid)
            if wifi_info and wifi_info.password:
                # 使用nmcli连接WiFi
                result = subprocess.run(['nmcli', 'device', 'wifi', 'connect', ssid, 
                                       'password', wifi_info.password], 
                                       capture_output=True, text=True, timeout=30)
                if result.returncode == 0:
                    return True
                else:
                    QMessageBox.warning(None, "警告", f"连接WiFi错误: {result.stderr}")
                    return False
            elif wifi_info:
                # 尝试无密码连接
                result = subprocess.run(['nmcli', 'device', 'wifi', 'connect', ssid], 
                                       capture_output=True, text=True, timeout=30)
                if result.returncode == 0:
                    return True
                else:
                    QMessageBox.warning(None, "警告", f"连接WiFi错误: {result.stderr}")
                    return False
            return False
        except subprocess.TimeoutExpired:
            QMessageBox.warning(None, "警告", "连接WiFi超时")
            return False
        except FileNotFoundError:
            QMessageBox.critical(None, "错误", "找不到nmcli命令，请安装NetworkManager。")
            return False
        except Exception as e:
            QMessageBox.warning(None, "警告", f"连接WiFi时出错: {e}")
            return False
    
    # 新增一个带密码连接并保存配置的方法
    def connect_and_save_wifi(self, ssid, password):
        """使用指定密码连接WiFi并在连接成功后保存配置"""
        try:
            # 检查是否已经连接到该WiFi
            current_wifi = self.get_current_connected_wifi()
            if current_wifi == ssid:
                QMessageBox.information(None, "信息", f"已经连接到 {ssid}")
                # 仍然保存配置
                self.add_wifi(ssid, password)
                return True
                
            result = subprocess.run(['nmcli', 'device', 'wifi', 'connect', ssid, 
                                   'password', password], 
                                   capture_output=True, text=True, timeout=30)
            if result.returncode == 0:
                # 连接成功后保存配置
                self.add_wifi(ssid, password)
                return True
            else:
                QMessageBox.warning(None, "警告", f"连接WiFi错误: {result.stderr}")
                return False
        except subprocess.TimeoutExpired:
            QMessageBox.warning(None, "警告", "连接WiFi超时")
            return False
        except FileNotFoundError:
            QMessageBox.critical(None, "错误", "找不到nmcli命令，请安装NetworkManager。")
            return False
        except Exception as e:
            QMessageBox.warning(None, "警告", f"连接WiFi时出错: {e}")
            return False
    
    def get_current_connected_wifi(self):
        """获取当前连接的WiFi名称"""
        try:
            # 使用nmcli命令获取当前连接的WiFi
            result = subprocess.run(['nmcli', '--terse', '--fields', 'NAME,DEVICE,STATE,TYPE', 'connection', 'show', '--active'], 
                                   capture_output=True, text=True, timeout=10)
            if result.returncode == 0:
                for line in result.stdout.strip().split('\n'):
                    if line:
                        parts = line.split(':')
                        # 需要检查至少4个字段(NAME, DEVICE, STATE, TYPE)
                        if len(parts) >= 4 and parts[2] == "activated" and parts[3] == "802-11-wireless":
                            return parts[0]  # 返回连接名称
                return None
            else:
                QMessageBox.warning(None, "警告", f"获取当前连接错误: {result.stderr}")
                return None
        except subprocess.TimeoutExpired:
            QMessageBox.warning(None, "警告", "获取当前连接超时")
            return None
        except FileNotFoundError:
            QMessageBox.critical(None, "错误", "找不到nmcli命令，请安装NetworkManager。")
            return None
        except Exception as e:
            QMessageBox.warning(None, "警告", f"获取当前连接时出错: {e}")
            return None

class WiFiDialog(QDialog):
    def __init__(self, manager, parent=None):
        super().__init__(parent)
        self.manager = manager
        self.current_ssid = ""
        self.init_ui()
    
    def init_ui(self):
        self.setWindowTitle("WiFi配置")
        
        # 添加页面标题
        title_label = QLabel("WiFi配置")
        title_font = QFont()
        title_font.setPointSize(16)
        title_font.setBold(True)
        title_label.setFont(title_font)
        title_label.setAlignment(Qt.AlignCenter)
        
        # 创建UI元素
        self.ssid_edit = QLineEdit(self)
        self.password_edit = QLineEdit(self)
        self.password_edit.setEchoMode(QLineEdit.Password)
        self.view_password_button = QPushButton("查看", self)
        
        self.use_static_ip_checkbox = QCheckBox("使用静态IP", self)
        self.ip_address_edit = QLineEdit(self)
        self.gateway_edit = QLineEdit(self)
        
        # 添加备注字段
        self.remark_edit = QTextEdit(self)
        self.remark_edit.setMaximumHeight(100)
        
        self.save_button = QPushButton("保存", self)
        self.cancel_button = QPushButton("取消", self)
        
        # 布局
        form_layout = QFormLayout()
        form_layout.addRow(title_label)
        form_layout.addRow("SSID(WiFi名称):", self.ssid_edit)
        
        password_layout = QHBoxLayout()
        password_layout.addWidget(self.password_edit)
        password_layout.addWidget(self.view_password_button)
        form_layout.addRow("密码:", password_layout)
        
        form_layout.addRow(self.use_static_ip_checkbox)
        form_layout.addRow("IP地址:", self.ip_address_edit)
        form_layout.addRow("网关:", self.gateway_edit)
        form_layout.addRow("备注:", self.remark_edit)  # 添加备注字段
        
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        button_layout.addWidget(self.save_button)
        button_layout.addWidget(self.cancel_button)
        
        main_layout = QVBoxLayout()
        main_layout.addLayout(form_layout)
        main_layout.addLayout(button_layout)
        
        self.setLayout(main_layout)
        
        # 连接信号槽
        self.save_button.clicked.connect(self.on_save_clicked)
        self.cancel_button.clicked.connect(self.reject)
        self.view_password_button.clicked.connect(self.on_view_password_clicked)
        self.use_static_ip_checkbox.stateChanged.connect(self.on_use_static_ip_changed)
        
        # 初始化状态
        self.on_use_static_ip_changed(self.use_static_ip_checkbox.isChecked())
    
    def set_current_wifi(self, ssid):
        self.current_ssid = ssid
        self.ssid_edit.setText(ssid)
        self.ssid_edit.setReadOnly(True)
        
        if ssid:
            info = self.manager.get_wifi_info(ssid)
            self.password_edit.setText(info.password)
            self.use_static_ip_checkbox.setChecked(info.use_static_ip)
            self.ip_address_edit.setText(info.ip_address)
            self.gateway_edit.setText(info.gateway)
            self.remark_edit.setPlainText(info.remark)  # 设置备注信息
        
        self.update_ui()
    
    def update_ui(self):
        use_static = self.use_static_ip_checkbox.isChecked()
        self.ip_address_edit.setEnabled(use_static)
        self.gateway_edit.setEnabled(use_static)
    
    def on_view_password_clicked(self):
        if self.password_edit.echoMode() == QLineEdit.Password:
            self.password_edit.setEchoMode(QLineEdit.Normal)
            self.view_password_button.setText("隐藏")
        else:
            self.password_edit.setEchoMode(QLineEdit.Password)
            self.view_password_button.setText("查看")
    
    def on_use_static_ip_changed(self, state):
        self.update_ui()
    
    def on_save_clicked(self):
        ssid = self.ssid_edit.text().strip()
        if not ssid:
            QMessageBox.warning(self, "警告", "SSID(WiFi名称)不能为空！")
            return
        
        password = self.password_edit.text()
        remark = self.remark_edit.toPlainText()  # 获取备注信息
        
        # 保存WiFi配置，包括备注
        self.manager.add_wifi(ssid, password)
        wifi_info = self.manager.wifi_configs[ssid]
        wifi_info.remark = remark
        self.manager.set_static_ip_config(
            ssid, 
            self.use_static_ip_checkbox.isChecked(),
            self.ip_address_edit.text(), 
            self.gateway_edit.text()
        )
        self.manager.save_config()
        
        # 确保保存后立即刷新主窗口的WiFi列表
        self._refresh_parent_wifi_list()
        
        self.accept()
    
    def _refresh_parent_wifi_list(self):
        """
        刷新父窗口的WiFi列表
        支持从不同层级的窗口打开此对话框的情况
        """
        # 检查直接父窗口
        parent_window = self.parent()
        if parent_window and hasattr(parent_window, 'update_wifi_list'):
            parent_window.update_wifi_list()
            return
            
        # 检查父窗口的父窗口（如通过扫描窗口打开的情况）
        if (parent_window and hasattr(parent_window, 'parent') and 
            parent_window.parent() and hasattr(parent_window.parent(), 'update_wifi_list')):
            parent_window.parent().update_wifi_list()
            return
            
        # 检查父窗口的父窗口的父窗口（更深层嵌套的情况）
        if (parent_window and hasattr(parent_window, 'parent') and 
            parent_window.parent() and hasattr(parent_window.parent(), 'parent') and
            parent_window.parent().parent() and hasattr(parent_window.parent().parent(), 'update_wifi_list')):
            parent_window.parent().parent().update_wifi_list()

class WiFiScanWorker(QThread):
    scan_finished = pyqtSignal(list)
    scan_error = pyqtSignal(str)
    
    def __init__(self, manager):
        super().__init__()
        self.manager = manager
    
    def run(self):
        try:
            wifi_list = self.manager.get_wifi_list()
            self.scan_finished.emit(wifi_list)
        except Exception as e:
            self.scan_error.emit(f"扫描时出错: {str(e)}")

class WiFiScanWindow(QDialog):
    def __init__(self, manager, parent=None):
        super().__init__(parent)
        self.manager = manager
        self.scan_worker = None
        self.init_ui()
        self.scan_wifi()
    
    def init_ui(self):
        self.setWindowTitle("扫描WiFi")
        self.resize(400, 300)
        
        # 添加页面标题
        title_label = QLabel("扫描可用WiFi网络")
        title_font = QFont()
        title_font.setPointSize(16)
        title_font.setBold(True)
        title_label.setFont(title_font)
        title_label.setAlignment(Qt.AlignCenter)
        
        layout = QVBoxLayout()
        layout.addWidget(title_label)  # 添加标题
        
        self.wifi_list_widget = QListWidget(self)
        
        # 添加进度条用于显示扫描状态
        self.progress_bar = QProgressBar(self)
        self.progress_bar.setRange(0, 0)  # 设置为不确定模式
        self.progress_bar.setVisible(False)
        self.progress_label = QLabel("正在扫描WiFi网络...", self)
        self.progress_label.setVisible(False)
        self.progress_label.setAlignment(Qt.AlignCenter)
        
        layout.addWidget(self.progress_label)
        layout.addWidget(self.progress_bar)
        layout.addWidget(self.wifi_list_widget)
        
        button_layout = QHBoxLayout()
        self.connect_button = QPushButton("连接", self)
        self.save_button = QPushButton("保存", self)  # 添加保存按钮
        self.refresh_button = QPushButton("刷新", self)
        self.close_button = QPushButton("关闭", self)
        
        button_layout.addWidget(self.connect_button)
        button_layout.addWidget(self.save_button)  # 添加保存按钮到布局
        button_layout.addWidget(self.refresh_button)
        button_layout.addWidget(self.close_button)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
        
        # 连接信号槽
        self.connect_button.clicked.connect(self.on_connect_clicked)
        self.save_button.clicked.connect(self.on_save_clicked)  # 连接保存功能
        self.refresh_button.clicked.connect(self.scan_wifi)
        self.close_button.clicked.connect(self.accept)
        self.wifi_list_widget.itemDoubleClicked.connect(self.on_connect_clicked)
    
    def scan_wifi(self):
        # 显示加载状态
        self.progress_bar.setVisible(True)
        self.progress_label.setVisible(True)
        self.wifi_list_widget.setVisible(False)
        self.refresh_button.setEnabled(False)
        self.refresh_button.setText("扫描中...")
        
        # 使用线程执行扫描任务
        self.scan_worker = WiFiScanWorker(self.manager)
        self.scan_worker.scan_finished.connect(self.on_scan_finished)
        self.scan_worker.scan_error.connect(self.on_scan_error)
        self.scan_worker.start()
    
    def on_scan_finished(self, wifi_list):
        # 隐藏加载状态
        self.progress_bar.setVisible(False)
        self.progress_label.setVisible(False)
        self.wifi_list_widget.setVisible(True)
        self.refresh_button.setEnabled(True)
        self.refresh_button.setText("刷新")
        
        # 更新WiFi列表
        self.wifi_list_widget.clear()
        for wifi in wifi_list:
            self.wifi_list_widget.addItem(wifi)
    
    def on_scan_error(self, error_msg):
        # 隐藏加载状态
        self.progress_bar.setVisible(False)
        self.progress_label.setVisible(False)
        self.wifi_list_widget.setVisible(True)
        self.refresh_button.setEnabled(True)
        self.refresh_button.setText("刷新")
        
        QMessageBox.critical(self, "扫描错误", f"扫描WiFi时出错: {error_msg}")
    
    def on_connect_clicked(self):
        current_item = self.wifi_list_widget.currentItem()
        if current_item:
            ssid = current_item.text()
            # 检查是否已保存配置
            if ssid in self.manager.wifi_configs:
                # 使用已保存的配置连接
                if self.manager.connect_wifi(ssid):
                    QMessageBox.information(self, "成功", f"成功连接到 {ssid}")
                    self._refresh_main_window_list()
                    self.accept()
                else:
                    QMessageBox.critical(self, "错误", f"连接到 {ssid} 失败")
            else:
                # 弹出密码输入框
                # 创建自定义密码输入对话框以支持显示/隐藏功能
                dialog = QDialog(self)
                dialog.setWindowTitle(f"输入 {ssid} 的密码")
                dialog.setModal(True)
                dialog.resize(300, 100)
                
                layout = QVBoxLayout()
                
                # 添加页面标题
                title_label = QLabel(f"请输入 {ssid} 的密码")
                title_font = QFont()
                title_font.setPointSize(12)
                title_font.setBold(True)
                title_label.setFont(title_font)
                title_label.setAlignment(Qt.AlignCenter)
                layout.addWidget(title_label)
                
                # 密码输入区域
                password_layout = QHBoxLayout()
                password_edit = QLineEdit()
                password_edit.setEchoMode(QLineEdit.Password)
                view_password_button = QPushButton("查看")
                
                password_layout.addWidget(password_edit)
                password_layout.addWidget(view_password_button)
                
                layout.addLayout(password_layout)
                
                # 按钮区域
                button_layout = QHBoxLayout()
                ok_button = QPushButton("确定")
                cancel_button = QPushButton("取消")
                button_layout.addWidget(ok_button)
                button_layout.addWidget(cancel_button)
                layout.addLayout(button_layout)
                
                dialog.setLayout(layout)
                
                # 连接信号槽
                def toggle_password_visibility():
                    if password_edit.echoMode() == QLineEdit.Password:
                        password_edit.setEchoMode(QLineEdit.Normal)
                        view_password_button.setText("隐藏")
                    else:
                        password_edit.setEchoMode(QLineEdit.Password)
                        view_password_button.setText("查看")
                
                def accept_dialog():
                    if password_edit.text():
                        dialog.accept()
                
                view_password_button.clicked.connect(toggle_password_visibility)
                ok_button.clicked.connect(accept_dialog)
                cancel_button.clicked.connect(dialog.reject)
                password_edit.returnPressed.connect(accept_dialog)  # 回车确认
                
                if dialog.exec_() == QDialog.Accepted:
                    password = password_edit.text()
                    # 使用新方法连接并保存配置
                    if self.manager.connect_and_save_wifi(ssid, password):
                        QMessageBox.information(self, "成功", f"成功连接到 {ssid} 并已保存配置")
                        self._refresh_main_window_list()
                        self.accept()
                    else:
                        QMessageBox.critical(self, "错误", f"连接到 {ssid} 失败")
    
    def _refresh_main_window_list(self):
        """刷新主窗口的WiFi列表"""
        main_window = self._find_main_window()
        if main_window:
            main_window.update_wifi_list()
    
    def _find_main_window(self):
        """查找主窗口实例"""
        parent = self.parent()
        while parent:
            if isinstance(parent, WiFiMainWindow):
                return parent
            parent = parent.parent()
        return None

    # 添加保存WiFi功能
    def on_save_clicked(self):
        current_item = self.wifi_list_widget.currentItem()
        if current_item:
            ssid = current_item.text()
            # 检查WiFi是否已经保存
            if ssid in self.manager.wifi_configs:
                reply = QMessageBox.question(self, "确认", f"WiFi {ssid} 已存在，是否要更新配置？",
                                           QMessageBox.Yes | QMessageBox.No)
                if reply == QMessageBox.No:
                    return
            
            # 打开WiFi配置对话框
            dialog = WiFiDialog(self.manager, self)
            dialog.set_current_wifi(ssid)
            if dialog.exec_() == QDialog.Accepted:
                QMessageBox.information(self, "成功", f"WiFi {ssid} 已保存")
                self._refresh_main_window_list()

class WiFiMainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.wifi_manager = WiFiManager()
        self.init_ui()
        self.update_wifi_list()
        
        self.setWindowTitle("WiFi管理器")
        self.resize(500, 400)
        
        # 居中显示窗口
        self.center_window()
        
        # 添加定时器，每5秒更新一次WiFi列表
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.on_update_wifi_list)
        self.timer.start(5000)  # 5秒更新一次
    
    def center_window(self):
        """将窗口居中显示"""
        qr = self.frameGeometry()
        cp = QApplication.desktop().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
    
    def init_ui(self):
        # 使用标签页组织界面
        self.tab_widget = QTabWidget()
        self.setCentralWidget(self.tab_widget)
        
        # 创建WiFi管理标签页
        self.create_wifi_tab()
        
        # 创建帮助文档标签页
        self.create_help_tab()
        
        # 添加状态栏显示当前页面
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.status_bar.showMessage("当前页面: 已保存WiFi列表")
        
        # 连接标签页切换信号
        self.tab_widget.currentChanged.connect(self.on_tab_changed)
    
    def create_wifi_tab(self):
        # 创建WiFi管理页面
        wifi_widget = QWidget()
        
        # 添加页面标题
        title_label = QLabel("已保存的WiFi网络")
        title_font = QFont()
        title_font.setPointSize(16)
        title_font.setBold(True)
        title_label.setFont(title_font)
        title_label.setAlignment(Qt.AlignCenter)
        
        self.wifi_list_widget = QListWidget(self)
        
        self.add_button = QPushButton("添加WiFi", self)
        self.edit_button = QPushButton("编辑WiFi", self)
        self.remove_button = QPushButton("删除WiFi", self)
        self.connect_button = QPushButton("连接WiFi", self)
        
        # 添加断开WiFi连接按钮
        self.disconnect_button = QPushButton("断开连接", self)
        self.disconnect_button.clicked.connect(self.on_disconnect_wifi)
        
        # 添加扫描WiFi按钮
        scan_button = QPushButton("扫描WiFi", self)
        
        # 添加导入/导出按钮
        import_button = QPushButton("导入配置", self)
        export_button = QPushButton("导出配置", self)
        
        # 添加保存当前连接WiFi按钮
        self.save_current_button = QPushButton("保存当前连接", self)
        self.save_current_button.setVisible(False)  # 默认隐藏
        self.current_ssid = None  # 保存当前连接的SSID
        
        button_layout = QVBoxLayout()
        button_layout.addWidget(self.add_button)
        button_layout.addWidget(self.edit_button)
        button_layout.addWidget(self.remove_button)
        button_layout.addWidget(self.connect_button)
        button_layout.addWidget(self.disconnect_button)  # 添加断开连接按钮
        button_layout.addWidget(scan_button)
        button_layout.addWidget(self.save_current_button)  # 添加保存当前连接按钮
        button_layout.addWidget(import_button)
        button_layout.addWidget(export_button)
        button_layout.addStretch()
        
        main_layout = QVBoxLayout()
        main_layout.addWidget(title_label)  # 添加标题
        h_layout = QHBoxLayout()
        h_layout.addWidget(self.wifi_list_widget, 1)
        h_layout.addLayout(button_layout)
        main_layout.addLayout(h_layout)
        
        wifi_widget.setLayout(main_layout)
        
        # 连接信号槽
        self.add_button.clicked.connect(self.on_add_wifi)
        self.edit_button.clicked.connect(self.on_edit_wifi)
        self.remove_button.clicked.connect(self.on_remove_wifi)
        self.connect_button.clicked.connect(self.on_connect_wifi)
        self.wifi_list_widget.itemDoubleClicked.connect(self.on_connect_wifi)
        scan_button.clicked.connect(self.on_scan_wifi)
        import_button.clicked.connect(self.on_import_config)
        export_button.clicked.connect(self.on_export_config)
        self.save_current_button.clicked.connect(self.on_save_current_wifi)  # 连接保存当前连接WiFi功能
        
        # 将WiFi标签页添加到标签控件
        self.tab_widget.addTab(wifi_widget, "WiFi管理")
    
    def create_help_tab(self):
        # 创建软件说明页面
        help_widget = QWidget()
        help_layout = QVBoxLayout()
        
        # 添加页面标题
        title_label = QLabel("软件说明")
        title_font = QFont()
        title_font.setPointSize(16)
        title_font.setBold(True)
        title_label.setFont(title_font)
        title_label.setAlignment(Qt.AlignCenter)
        
        # 创建文本浏览器显示README内容
        self.help_text_browser = QTextBrowser()
        self.help_text_browser.setOpenExternalLinks(True)
        
        # 加载README文档内容
        try:
            with open(os.path.join(os.path.dirname(__file__), "README.md"), 'r', encoding='utf-8') as f:
                readme_content = f.read()
                # 简单的Markdown到HTML转换
                html_content = self.format_readme_content(readme_content)
                self.help_text_browser.setHtml(html_content)
        except Exception as e:
            self.help_text_browser.setPlainText(f"无法加载帮助文档: {str(e)}")
        
        help_layout.addWidget(title_label)
        help_layout.addWidget(self.help_text_browser)
        help_widget.setLayout(help_layout)
        
        # 将软件说明标签页添加到标签控件
        self.tab_widget.addTab(help_widget, "软件说明")
    
    def format_readme_content(self, content):
        """将Markdown内容转换为HTML格式"""
        import re
        
        # 转换为HTML
        html_content = content
        
        # 处理代码块 (``code```)
        code_block_pattern = re.compile(r'```(\w+)?\n(.*?)```', re.DOTALL)
        def code_block_replacer(match):
            lang = match.group(1) or 'text'
            code = match.group(2)
            return f'<pre><code class="{lang}">{code}</code></pre>'
        html_content = code_block_pattern.sub(code_block_replacer, html_content)
        
        # 处理行内代码 (`code`)
        html_content = re.sub(r'`([^`]+)`', r'<code>\1</code>', html_content)
        
        # 处理Markdown链接 [text](url)
        html_content = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<a href="\2">\1</a>', html_content)
        
        # 处理粗体 (**text** 或 __text__)
        html_content = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', html_content)
        html_content = re.sub(r'__(.*?)__', r'<strong>\1</strong>', html_content)
        
        # 处理斜体 (*text* 或 _text_)
        html_content = re.sub(r'\*(.*?)\*', r'<em>\1</em>', html_content)
        html_content = re.sub(r'_(.*?)_', r'<em>\1</em>', html_content)
        
        # 处理标题 (# H1, ## H2, ### H3等)
        html_content = re.sub(r'^######\s+(.*)', r'<h6>\1</h6>', html_content, flags=re.MULTILINE)
        html_content = re.sub(r'^#####\s+(.*)', r'<h5>\1</h5>', html_content, flags=re.MULTILINE)
        html_content = re.sub(r'^####\s+(.*)', r'<h4>\1</h4>', html_content, flags=re.MULTILINE)
        html_content = re.sub(r'^###\s+(.*)', r'<h3>\1</h3>', html_content, flags=re.MULTILINE)
        html_content = re.sub(r'^##\s+(.*)', r'<h2>\1</h2>', html_content, flags=re.MULTILINE)
        html_content = re.sub(r'^#\s+(.*)', r'<h1>\1</h1>', html_content, flags=re.MULTILINE)
        
        # 处理无序列表 (- item 或 * item)
        html_content = re.sub(r'^\s*[-\*]\s+(.*)', r'<li>\1</li>', html_content, flags=re.MULTILINE)
        # 包装<li>项到<ul>标签中
        html_content = re.sub(r'(<li>.*?</li>\n?)+', r'<ul>\g<0></ul>', html_content, flags=re.MULTILINE)
        
        # 处理有序列表 (1. item)
        html_content = re.sub(r'^\s*\d+\.\s+(.*)', r'<li>\1</li>', html_content, flags=re.MULTILINE)
        # 包装<li>项到<ol>标签中
        html_content = re.sub(r'(<li>.*?</li>\n?)+', r'<ol>\g<0></ol>', html_content, flags=re.MULTILINE)
        
        # 处理段落 (空行分隔的文本块)
        paragraphs = html_content.split('\n\n')
        processed_paragraphs = []
        for p in paragraphs:
            if not re.match(r'<.*?>', p.strip()):  # 如果不是HTML标签
                p = f'<p>{p}</p>'
            processed_paragraphs.append(p)
        html_content = '\n\n'.join(processed_paragraphs)
        
        # 添加基本样式
        styled_html = f"""
        <style>
            body {{
                font-family: "Microsoft YaHei", sans-serif;
                line-height: 1.6;
                padding: 20px;
            }}
            h1, h2, h3, h4, h5, h6 {{
                color: #333;
                margin-top: 24px;
                margin-bottom: 16px;
            }}
            h1 {{
                font-size: 2em;
                border-bottom: 1px solid #eee;
                padding-bottom: 10px;
            }}
            h2 {{
                font-size: 1.5em;
                border-bottom: 1px solid #eee;
                padding-bottom: 8px;
            }}
            h3 {{
                font-size: 1.25em;
            }}
            p {{
                margin: 10px 0;
            }}
            a {{
                color: #4078c0;
                text-decoration: none;
            }}
            a:hover {{
                text-decoration: underline;
            }}
            code {{
                background-color: #f6f8fa;
                padding: 2px 4px;
                border-radius: 3px;
                font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
                font-size: 0.9em;
            }}
            pre {{
                background-color: #f6f8fa;
                padding: 16px;
                overflow: auto;
                border-radius: 6px;
                font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
                font-size: 0.9em;
            }}
            ul, ol {{
                padding-left: 2em;
            }}
            li {{
                margin: 5px 0;
            }}
        </style>
        <div class="markdown-body">
            {html_content}
        </div>
        """
        
        return styled_html

    def on_tab_changed(self, index):
        # 根据当前标签页更新状态栏
        tab_text = self.tab_widget.tabText(index)
        self.status_bar.showMessage(f"当前页面: {tab_text}")
        
        # 如果切换到WiFi管理页面，更新WiFi列表
        if tab_text == "WiFi管理":
            self.update_wifi_list()
    
    def update_wifi_list(self):
        self.wifi_list_widget.clear()
        
        # 获取当前连接的WiFi
        current_wifi = self.wifi_manager.get_current_connected_wifi()
        self.current_ssid = current_wifi
        
        # 如果当前连接的WiFi不在已保存列表中，显示保存按钮
        if current_wifi and current_wifi not in self.wifi_manager.wifi_configs:
            self.save_current_button.setVisible(True)
            self.save_current_button.setText(f"保存当前连接: {current_wifi}")
        else:
            self.save_current_button.setVisible(False)
        
        # 显示已保存的WiFi列表
        for ssid, wifi_info in self.wifi_manager.wifi_configs.items():
            # 显示WiFi名称和备注信息
            display_text = ssid
            if wifi_info.remark:
                display_text += f" ({wifi_info.remark})"
            
            # 如果这是当前连接的WiFi，添加标记
            if ssid == current_wifi:
                display_text = f"{display_text} (当前连接)"
            
            self.wifi_list_widget.addItem(display_text)
            
            # 如果这是当前连接的WiFi，设置特殊颜色
            if ssid == current_wifi:
                item = self.wifi_list_widget.item(self.wifi_list_widget.count() - 1)
                font = item.font()
                font.setBold(True)
                item.setFont(font)
                item.setForeground(QColor(0, 128, 0))  # 深绿色
        
        # 如果当前连接的WiFi不在已保存列表中，也显示在列表顶部
        if current_wifi and current_wifi not in self.wifi_manager.wifi_configs:
            display_text = f"{current_wifi} (未保存)"
            # 添加已连接标记
            display_text = f"[已连接] {display_text}"
            self.wifi_list_widget.insertItem(0, display_text)
            
            # 设置特殊颜色和粗体显示
            item = self.wifi_list_widget.item(0)
            font = item.font()
            font.setBold(True)
            item.setFont(font)
            item.setForeground(QColor(0, 128, 0))  # 深绿色
    
    def on_update_wifi_list(self):
        # 只有在WiFi管理标签页时才更新列表
        if self.tab_widget.currentIndex() == 0:  # WiFi管理标签页索引为0
            self.update_wifi_list()
    
    def on_add_wifi(self):
        dialog = WiFiDialog(self.wifi_manager, self)
        dialog.setWindowTitle("添加WiFi")
        dialog.ssid_edit.setReadOnly(False)
        if dialog.exec_() == QDialog.Accepted:
            self.update_wifi_list()
        self.status_bar.showMessage("当前页面: 已保存WiFi列表")  # 返回主界面时更新状态栏
    
    def on_edit_wifi(self):
        current_item = self.wifi_list_widget.currentItem()
        if not current_item:
            QMessageBox.warning(self, "警告", "请先选择一个WiFi网络！")
            return
        
        # 正确解析SSID，从显示文本中提取真实的SSID
        display_text = current_item.text()
        # 如果显示文本包含备注，需要提取原始SSID
        if " (" in display_text and display_text.endswith(")"):
            ssid = display_text.split(" (")[0]
        else:
            ssid = display_text
            
        dialog = WiFiDialog(self.wifi_manager, self)
        dialog.set_current_wifi(ssid)
        if dialog.exec_() == QDialog.Accepted:
            self.update_wifi_list()
        self.status_bar.showMessage("当前页面: 已保存WiFi列表")  # 返回主界面时更新状态栏
    
    def on_remove_wifi(self):
        current_item = self.wifi_list_widget.currentItem()
        if not current_item:
            QMessageBox.warning(self, "警告", "请先选择一个WiFi网络！")
            return
        
        # 正确解析SSID
        display_text = current_item.text()
        if " (" in display_text and display_text.endswith(")"):
            ssid = display_text.split(" (")[0]
        else:
            ssid = display_text
        
        reply = QMessageBox.question(self, "确认", f"确定要删除 {ssid} 吗？",
                                   QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.wifi_manager.remove_wifi(ssid)
            self.update_wifi_list()
    
    def on_connect_wifi(self):
        current_item = self.wifi_list_widget.currentItem()
        if not current_item:
            QMessageBox.warning(self, "警告", "请先选择一个WiFi网络！")
            return
        
        # 正确解析SSID
        display_text = current_item.text()
        if " (" in display_text and display_text.endswith(")"):
            ssid = display_text.split(" (")[0]
        else:
            ssid = display_text
            
        # 检查是否已保存配置
        if ssid in self.wifi_manager.wifi_configs:
            # 使用已保存的配置连接
            if self.wifi_manager.connect_wifi(ssid):
                QMessageBox.information(self, "成功", f"成功连接到 {ssid}")
                self.update_wifi_list()
            else:
                QMessageBox.critical(self, "错误", f"连接到 {ssid} 失败")
        else:
            # 弹出密码输入框
            from PyQt5.QtWidgets import QInputDialog, QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton  # 添加导入
            # 创建自定义密码输入对话框以支持显示/隐藏功能
            dialog = QDialog(self)
            dialog.setWindowTitle(f"输入 {ssid} 的密码")
            dialog.setModal(True)
            dialog.resize(300, 100)
            
            layout = QVBoxLayout()
            
            # 添加页面标题
            title_label = QLabel(f"请输入 {ssid} 的密码")
            title_font = QFont()
            title_font.setPointSize(12)
            title_font.setBold(True)
            title_label.setFont(title_font)
            title_label.setAlignment(Qt.AlignCenter)
            layout.addWidget(title_label)
            
            # 密码输入区域
            password_layout = QHBoxLayout()
            password_edit = QLineEdit()
            password_edit.setEchoMode(QLineEdit.Password)
            view_password_button = QPushButton("查看")
            
            password_layout.addWidget(password_edit)
            password_layout.addWidget(view_password_button)
            
            layout.addLayout(password_layout)
            
            # 按钮区域
            button_layout = QHBoxLayout()
            ok_button = QPushButton("确定")
            cancel_button = QPushButton("取消")
            button_layout.addWidget(ok_button)
            button_layout.addWidget(cancel_button)
            layout.addLayout(button_layout)
            
            dialog.setLayout(layout)
            
            # 连接信号槽
            def toggle_password_visibility():
                if password_edit.echoMode() == QLineEdit.Password:
                    password_edit.setEchoMode(QLineEdit.Normal)
                    view_password_button.setText("隐藏")
                else:
                    password_edit.setEchoMode(QLineEdit.Password)
                    view_password_button.setText("查看")
            
            def accept_dialog():
                if password_edit.text():
                    dialog.accept()
            
            view_password_button.clicked.connect(toggle_password_visibility)
            ok_button.clicked.connect(accept_dialog)
            cancel_button.clicked.connect(dialog.reject)
            password_edit.returnPressed.connect(accept_dialog)  # 回车确认
            
            if dialog.exec_() == QDialog.Accepted:
                password = password_edit.text()
                # 使用新方法连接并保存配置
                if self.wifi_manager.connect_and_save_wifi(ssid, password):
                    QMessageBox.information(self, "成功", f"成功连接到 {ssid} 并已保存配置")
                    self.update_wifi_list()  # 更新列表以显示新添加的WiFi
                else:
                    QMessageBox.critical(self, "错误", f"连接到 {ssid} 失败")
    
    def on_disconnect_wifi(self):
        """断开当前WiFi连接"""
        try:
            # 获取当前连接的WiFi
            current_wifi = self.wifi_manager.get_current_connected_wifi()
            if not current_wifi:
                QMessageBox.information(self, "信息", "当前没有连接到任何WiFi网络")
                return
            
            # 使用nmcli断开WiFi连接
            result = subprocess.run(['nmcli', 'device', 'disconnect', 'wifi0'], 
                                   capture_output=True, text=True, timeout=10)
            if result.returncode == 0:
                QMessageBox.information(self, "成功", f"已断开WiFi连接: {current_wifi}")
                self.update_wifi_list()
            else:
                # 如果wifi0失败，尝试使用通用方法
                result = subprocess.run(['nmcli', 'connection', 'down', current_wifi], 
                                       capture_output=True, text=True, timeout=10)
                if result.returncode == 0:
                    QMessageBox.information(self, "成功", f"已断开WiFi连接: {current_wifi}")
                    self.update_wifi_list()
                else:
                    QMessageBox.warning(self, "警告", f"断开WiFi连接失败: {result.stderr}")
        except subprocess.TimeoutExpired:
            QMessageBox.warning(self, "警告", "断开WiFi连接超时")
        except FileNotFoundError:
            QMessageBox.critical(self, "错误", "找不到nmcli命令，请安装NetworkManager。")
        except Exception as e:
            QMessageBox.warning(self, "警告", f"断开WiFi连接时出错: {e}")
    
    def on_scan_wifi(self):
        scan_window = WiFiScanWindow(self.wifi_manager, self)
        scan_window.exec_()
        self.status_bar.showMessage("当前页面: 已保存WiFi列表")  # 返回主界面时更新状态栏
    
    def on_import_config(self):
        file_path, _ = QFileDialog.getOpenFileName(self, "导入配置", "", "JSON Files (*.json)")
        if file_path:
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    for ssid, config in data.items():
                        self.wifi_manager.wifi_configs[ssid] = WiFiInfo(
                            ssid=config.get('ssid', ''),
                            password=config.get('password', ''),
                            use_static_ip=config.get('use_static_ip', False),
                            ip_address=config.get('ip_address', ''),
                            gateway=config.get('gateway', ''),
                            remark=config.get('remark', '')  # 添加备注信息导入
                        )
                    self.wifi_manager.save_config()
                    self.update_wifi_list()
                    QMessageBox.information(self, "成功", "配置导入成功！")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"导入配置失败: {str(e)}")
    
    def on_export_config(self):
        file_path, _ = QFileDialog.getSaveFileName(self, "导出配置", "wifimanager_config.json", "JSON Files (*.json)")
        if file_path:
            try:
                with open(file_path, 'w', encoding='utf-8') as f:
                    data = {}
                    for ssid, wifi_info in self.wifi_manager.wifi_configs.items():
                        data[ssid] = {
                            'ssid': wifi_info.ssid,
                            'password': wifi_info.password,
                            'use_static_ip': wifi_info.use_static_ip,
                            'ip_address': wifi_info.ip_address,
                            'gateway': wifi_info.gateway,
                            'remark': wifi_info.remark  # 添加备注信息导出
                        }
                    json.dump(data, f, indent=2, ensure_ascii=False)
                QMessageBox.information(self, "成功", "配置导出成功！")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"导出配置失败: {str(e)}")
    
    def on_save_current_wifi(self):
        """保存当前连接的WiFi"""
        if self.current_ssid:
            # 弹出密码输入框获取密码
            from PyQt5.QtWidgets import QInputDialog, QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton
            # 创建自定义密码输入对话框以支持显示/隐藏功能
            dialog = QDialog(self)
            dialog.setWindowTitle(f"输入 {self.current_ssid} 的密码")
            dialog.setModal(True)
            dialog.resize(300, 100)
            
            layout = QVBoxLayout()
            
            # 添加页面标题
            title_label = QLabel(f"请输入 {self.current_ssid} 的密码")
            title_font = QFont()
            title_font.setPointSize(12)
            title_font.setBold(True)
            title_label.setFont(title_font)
            title_label.setAlignment(Qt.AlignCenter)
            layout.addWidget(title_label)
            
            # 密码输入区域
            password_layout = QHBoxLayout()
            password_edit = QLineEdit()
            password_edit.setEchoMode(QLineEdit.Password)
            view_password_button = QPushButton("查看")
            
            password_layout.addWidget(password_edit)
            password_layout.addWidget(view_password_button)
            
            layout.addLayout(password_layout)
            
            # 按钮区域
            button_layout = QHBoxLayout()
            ok_button = QPushButton("确定")
            cancel_button = QPushButton("取消")
            button_layout.addWidget(ok_button)
            button_layout.addWidget(cancel_button)
            layout.addLayout(button_layout)
            
            dialog.setLayout(layout)
            
            # 连接信号槽
            def toggle_password_visibility():
                if password_edit.echoMode() == QLineEdit.Password:
                    password_edit.setEchoMode(QLineEdit.Normal)
                    view_password_button.setText("隐藏")
                else:
                    password_edit.setEchoMode(QLineEdit.Password)
                    view_password_button.setText("查看")
            
            def accept_dialog():
                if password_edit.text():
                    dialog.accept()
            
            view_password_button.clicked.connect(toggle_password_visibility)
            ok_button.clicked.connect(accept_dialog)
            cancel_button.clicked.connect(dialog.reject)
            password_edit.returnPressed.connect(accept_dialog)  # 回车确认
            
            if dialog.exec_() == QDialog.Accepted:
                password = password_edit.text()
                # 保存WiFi配置
                self.wifi_manager.add_wifi(self.current_ssid, password)
                # 弹出WiFi配置对话框让用户设置备注等信息
                dialog = WiFiDialog(self.wifi_manager, self)
                dialog.set_current_wifi(self.current_ssid)
                if dialog.exec_() == QDialog.Accepted:
                    QMessageBox.information(self, "成功", f"WiFi {self.current_ssid} 已保存")
                    self.update_wifi_list()

def main():
    app = QApplication(sys.argv)
    window = WiFiMainWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()